<?php

namespace Modules\Production\Repository;

use App\Services\InventoryService;
use App\Services\KingDeeService;
use App\Services\UnitService;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Modules\Base\Repository\BoxNumberRepository;
use Modules\Base\Repository\MaterialRepository;
use Modules\Production\Models\MaterialReturnDetail;
use Modules\Production\Models\MaterialReturnOrder;
use Modules\Production\Models\MaterialReturnPlanDetail;
use Modules\Production\Models\MaterialReturnPlanOrder;
use Modules\Production\Service\TaskScanService;
use App\Enums\InvTransDocType;

class MaterialReturnOrderRepository
{

    /**
     * 生产退料提交处理
     * @param $postData
     */
    static public function storeBy($postData){

        if(!is_array($postData) || empty($postData)){
            throw new \Exception('提交参数不能为空！');
        }

        try{
            DB::beginTransaction();

            $returnOrderNo = UnitService::createDocno('SCTL');
            //生产退料单据头创建
            $returnOrderId = (new MaterialReturnOrder())->storeBy([
                'docno' => $returnOrderNo
            ]);

            $returnOrderItem = [];

            $productionNo = '';
            foreach ($postData as $orderItem){

                if($productionNo != '' && $productionNo != $orderItem['production_no']){
                    throw new \Exception('同一提交工单号必须一致');
                }

                $productionNo = $orderItem['production_no'];

                foreach ($orderItem['detail'] as $detailItem){
                    $returnPlanOrder = MaterialReturnPlanOrderrRepository::getOrderDetailByDetailId($detailItem['plan_detail_id']);

                    $pickInfo = PickOrderRepository::getProductionNoByPickNo($returnPlanOrder->pick_order_no);

                    $lotnum = empty($detailItem['to_lot_num']) ? $returnPlanOrder->lot_num : trim($detailItem['to_lot_num']);
                    $unit = MaterialRepository::getUnitByMaterial($returnPlanOrder->material_no);

                    $returnOrderItem[] = [
                        'org_code'          => $pickInfo->org_code,
                        'cargo_type'        => $pickInfo->cargo_type,
                        'cargo_code'        => $pickInfo->cargo_code,
                        'order_id'          => $returnOrderId,
                        'material_no'       => $returnPlanOrder->material_no,
                        'unit'              => $unit,
                        'qty'               => $returnPlanOrder->qty,
                        'source_location'   => $returnPlanOrder->location,
                        'supplier_code'     => $returnPlanOrder->supplier_code,
                        'location'          => $detailItem['location'],
                        'source_lot_num'    => $returnPlanOrder->lot_num,
                        'lot_num'           => $lotnum,
                        'plan_order_no'     => $returnPlanOrder->order->docno,
                        'pick_order_no'     => $returnPlanOrder->pick_order_no,
                        'pick_order_id'     => $pickInfo->id,
                        'wms_code'          => TaskScanService::getWmsCodeByLocation($detailItem['location']),
                        'creator_id'        => Auth::guard(getGuardName())->id(),
                        'created_at'        => time(),
                        'updated_at'        => time(),
                    ];

                    //退料入库
                    InventoryService::addInv([
                        'org_code'      => $pickInfo->org_code,
                        'cargo_code'    => $pickInfo->cargo_code,
                        'supplier_code' => $returnPlanOrder->supplier_code,
                        'doc_id'        => $returnOrderId,
                        'docno'         => $returnOrderNo,
                        'doc_type'      => InvTransDocType::PRODUCTION_RETURN->value,
                        'material_no'   => $returnPlanOrder->material_no,
                        'location'      => $detailItem['location'],
                        'qty'           => $returnPlanOrder->qty,
                        'unit'          => $unit,
                        'lotnum'        => $lotnum,
                    ]);

                }

            }

            MaterialReturnDetail::insert($returnOrderItem);

            $printData = self::getBoxPrintData($returnOrderItem,$returnOrderNo);

            //推送金蝶
            self::pushKingdee($returnOrderId);

            DB::commit();
            return $printData;

        }catch (\Exception $e){
            DB::rollBack();
            throw $e;
        }
    }

    /**
     * 获取打印数据
     * @param $returnPlanItem
     * @return mixed
     */
    static public function getBoxPrintData($returnPlanItem,$returnOrderNo){

        foreach($returnPlanItem as &$val){
            $val['material']        = MaterialRepository::findMaterial($val['material_no']);
            $val['box']             = BoxNumberRepository::getBoxByCode($val['lot_num']);
            $val['production']      = PickOrderRepository::getProductionNoByPickNo($val['pick_order_no']);
            $val['print_date']      = date('Y-m-d');
            $val['return_order_no'] = $returnOrderNo;
        }

        return $returnPlanItem;
    }

    /**
     * 生产退料单据提送金蝶
     * @param $returnOrderId
     */
    static public function pushKingdee($returnOrderId){
        $returnOrder = self::getOrderExtendDetailByOrderId($returnOrderId);
        $orderDetail = self::getGroupByListByOrderId($returnOrder->id);

        $kingdeeItem = [];
        $orgCode = '';
        foreach ($orderDetail as $val){
            $orgCode = $val->org_code;
            $kingdeeItem[] = [
                'FOwnerTypeId'  => $val->cargo_type,
                'FOwnerId'      => $val->cargo_code,
                'FSRCBILLNO'    => $val->pick_order_no,
                'FMATERIALID'   => $val->material_no,
                'FUNITID'       => $val->unit,
                'FQTY'          => $val->qty,
                'FSTOCKID'      => $val->wms_code,
            ];
        }
        $order = [
            'FBILLTYPEID'   => 'PRD_ReturnMtrl',
            'FBILLNO'       => $returnOrder->docno,
            'FORGID'        => $orgCode,
            'FDATE'         => date('Y-m-d H:i:s'),
        ];
        $order['FEntity'] = $kingdeeItem;
        //print_r($order);exit();
        return (new KingDeeService())->form('TVJB_DJWMSDJ')->invokeSave($order);

    }

    /**
     * 根据生产退料单据id查询
     * @param $returnOrderId
     */
    static public function getOrderExtendDetailByOrderId($returnOrderId){
        return MaterialReturnOrder::with('detail')->find($returnOrderId);
    }

    /**
     * 根据生产退料单id汇总子项
     * @param $orderId
     * @return mixed
     */
    static public function getGroupByListByOrderId($orderId){
        return MaterialReturnDetail::select('org_code','cargo_type','cargo_code','material_no','unit','pick_order_no','wms_code',DB::raw('sum(qty) as qty'))
            ->where('order_id',$orderId)
            ->groupBy('org_code','cargo_type','cargo_code','material_no','unit','pick_order_no','wms_code')
            ->get();
    }
}
